function init_page(){
	init_menu();
	showContent('#home');
}
function init_menu(){
	var navigator = document.getElementById('navigator');
	navigator.addEventListener('click',
			function(event){
				var target = event.target;
				console.log(target.tagName);
				if (target.tagName != 'A'){
					return false;
				}
				var href = target.href;
				showContent(href);
			}, false);
}
var kind;
function showContent(href){
	var kinds = ['home', '@me', 'direct'];
	for ( i in kinds ){
		if (href.indexOf('#' + kinds[i]) != -1){
			kind = kinds[i];
			chrome.extension.sendRequest({action: 'get-tweets', kind: kind}, showTwits);
		}
	}
}

function showTwits(tweets){
	alert(tweets);
	var i, tweet;
	var uls = []
	for (i = 0; i < tweets.length; i++){
		tweet = tweets[i];
		uls.push(
			'<li><a href="#user-%s" title="%s"><img src="%s"/></a><p>%s</p><span>%s</span></li>'.format(
				tweet.user.screen_name,
				tweet.user.name,
				tweet.user.profile_image_url,
				tweet.text,
				tweet.created_at
			)
		)
	}
	document.getElementById(kind).innerHTML = '<ul>' + uls.join('') + '</ul>';
}

String.prototype.format = function(){
	var params = arguments, i = 0;
	return this.replace(/%s/g, function(){
			console.log(arguments);
				return params[i++] || arguments[0];
			})
}




function compose_area_init() {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    if (backend.isComposing) {
	if (backend.saveMessage != null)
	    document.getElementById("tweet_area_text").value = backend.saveMessage;
	toggle_compose_tweet_area(true);
    }
}

function onTextAreaChanged(event) {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    backend.saveMessage = document.getElementById("tweet_area_text").value;
  /*
    var availableChars = MAX_TWEET_SIZE - el.val().length;
    var charsLeftEl = $("#compose_tweet_area .chars_left");
    charsLeftEl.text(availableChars);
    if(availableChars < 0) {
      charsLeftEl.css('color', 'red');
      $("#compose_tweet_area input[type='button']").attr("disabled", "disabled");
    } else {
      charsLeftEl.css('color', 'black');
      $("#compose_tweet_area input[type='button']").removeAttr("disabled");
  */
    if(event && event.ctrlKey && event.which == 13) { // Ctrl + Enter
        sendTweet();
    }
}

function toggle_compose_tweet_area(showOnly) {
    var area = document.getElementById("compose_tweet_area");
    var visible = area.style.display == "none" ? false : true;
    if (!visible) {
        area.style.display = "";
        var left_img = document.getElementById("compose_tweet_left_img");
        left_img.src="img/arrow_up.gif";
        var right_img = document.getElementById("compose_tweet_right_img");
        right_img.src="img/arrow_up.gif";
    }
    else {
        area.style.display = "none";
        var left_img = document.getElementById("compose_tweet_left_img");
        left_img.src="img/arrow_down.gif";
        var right_img = document.getElementById("compose_tweet_right_img");
        right_img.src="img/arrow_down.gif";
    }
    if (!showOnly) {
	var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
	if (visible) {
	    document.getElementById("tweet_area_text").value = "";
	    backend.isComposing = false;
	    backend.saveMessage = "";
	    backend.replyId = null;
	    backend.retweetId = null;
	} else {
	    backend.isComposing = true;
	}
    }
}

function shortenURL() {
    chrome.tabs.getSelected(null, function(tab) {
        var shortenerInput = document.getElementById("shortener_area").children[0];
        if (shortenerInput.value == "Make a URL shorter (default is current page) Click ->" ||
            shortenerInput.value == "") {
            shortenerInput.value = tab.url;
        }

        var http = new XMLHttpRequest();
        var taburl = shortenerInput.value;
        http.open(
            "post",
            "http://goo.gl/api/url",
            true
        );
        http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        http.onload = function() {
            var shorturl = JSON.parse(http.responseText).short_url;
            console.log("shorter:" + shorturl)
            if (shorturl != undefined) {
                var tweet_text = document.getElementById("compose_tweet_area").children[0];
                if (tweet_text.value.length > 0 && tweet_text.value[tweet_text.value.length-1] != ' ') {
                    tweet_text.value = tweet_text.value + " " + shorturl;
                } else {
                    tweet_text.value = tweet_text.value + shorturl;
                }
            }
        }
        http.send(googl(taburl));
    });
}

function sendTweet() {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    var type = 0;
    if (backend.replyId != null) {
	type = 1;
    } else if (backend.retweetId != null) {
	type = 2;
    }

    var content = document.getElementById("tweet_area_text").value;

    var http = new XMLHttpRequest();
    http.open(
        "post",
        "http://t.163.com/statuses/update.json",
        true
    );
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
    http.onload = function() {
        if (http.status != 200 || http.responseText.length == 0 || http.responseText[0] != '{') {
	    console.log("status:" + http.status + http.responseText);
            return;
	}
        var res = eval('(' + http.responseText + ')');
        backend.home_max_id = res.id;
        backend.read[0].unshift(res);
        toggle_compose_tweet_area();
        showTweets(-1);
    }

    var body = "status=" + encodeURIComponent(content);
    if (type < 2) {
	body += "&in_reply_to_status_id=";
	if (type == 1) {
	    body += backend.replyId;
	}
    } else if (type == 2) {
	body += "&retweet_status_id=" + backend.retweetId;
    }
    body += "&source=<a href=\"http://code.google.com/p/chromet/\">Chromet</a>";
    http.send(body);
}

function replyTweet(node) {
    console.log("replying tweet");
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    var area = document.getElementById("compose_tweet_area");
    var visible = area.style.display == "none" ? false : true;
    if (!visible) {
	toggle_compose_tweet_area(true);
    }
    var textarea = document.getElementById("tweet_area_text");
    var old = textarea.value;
    if (old.length > 0 && old[length - 1] != ' ') {
	old += " ";
    }
    textarea.value = old + "@" + node.getAttribute("user_name") + " ";
    textarea.focus();
    textarea.setSelectionRange(textarea.value.length, textarea.value.length);
    backend.isComposing = true;
    backend.replyId = node.getAttribute("tweetid");
    backend.retweetId = null;
    onTextAreaChanged();
}

function deleteTweet(node) {
    console.log("delete tweet");
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    if (backend.del_confirm_node != null) {
	backend.del_confirm_node.style.display = "none";
    }
    backend.del_confirm_node = node.nextSibling.nextSibling;
    backend.del_confirm_node.style.display = "block";
}

function confirmDelete(type) {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    var tweet = backend.del_confirm_node.parentNode.parentNode;
    var tweetid = tweet.getAttribute("tweetid");
    console.log("confirm delete " + tweetid);
    backend.del_confirm_node.style.display = "none";
    backend.del_confirm_node = null;
    var url;
    if (type == 1) {
	url = "http://t.163.com/direct_messages/destroy/" + tweetid + ".json";
    } else {
	url = "http://t.163.com/statuses/destroy/" + tweetid + ".json";
    }

    var http = new XMLHttpRequest();
    http.open(
        "post",
	url,
        true
    );
    http.onload = function() {
	if (http.status == 200) {
	    if (type == 1) {
		backend.deleted_dm[tweetid] = 1;
	    } else {
		backend.deleted[tweetid] = 1;
	    }
	}
	showTweets(-1);
    }
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(null);

}

function denyDelete() {
    console.log("deny delete tweet");
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    backend.del_confirm_node.style.display = "none";
    backend.del_confirm_node = null;
}

function favTweet(node) {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    var tweetid = node.getAttribute("tweetid");
    var http = new XMLHttpRequest();
    http.open(
        "post",
        "http://t.163.com/favorites/create/" + tweetid + ".json",
        true
    );
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(null);
    console.log("fav tweet " + tweetid);
    backend.faved[tweetid] = 1;
    showTweets(-1);
}

function unfavTweet(node) {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    var tweetid = node.getAttribute("tweetid");
    var http = new XMLHttpRequest();
    http.open(
        "post",
        "http://t.163.com/favorites/destroy/" + tweetid + ".json",
        true
    );
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(null);
    console.log("unfav tweet " + tweetid);
    backend.faved[tweetid] = 0;
    showTweets(-1);
}

function shareTweet(node) {
    console.log("sharing tweet");
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;
    var area = document.getElementById("compose_tweet_area");
    var visible = area.style.display == "none" ? false : true;
    if (!visible) {
	toggle_compose_tweet_area(true);
    }
    var textarea = document.getElementById("tweet_area_text");
    var tweet = " 转@" + node.getAttribute("user_name") + "：";
    var textnode = node.children[0].children[2];
    tweet += textnode.innerText;
    document.getElementById("tweet_area_text").value = tweet;
    textarea.focus();
    textarea.setSelectionRange(0, 0);
    backend.isComposing = true;
    backend.retweetId = node.getAttribute("tweetid");
    backend.replyId = null;
    onTextAreaChanged();
}

function renderDM(dm) {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;

    TBASE = "http://t.163.com/";
    var sender = dm.sender;
    var text = dm.text;

    text = transformTweetText(text);
    var tweetClass = 'tweet';

    var str = '<div tweetid="' + dm.id + '" user_name="' +  sender.name + '" class="' + tweetClass + '" onmouseover="this.children[1].className=\'new_actions1\';"'
	+ ' onmouseout="this.children[1].className=\'new_actions0\';" >';
    str += '<div class="first_container">';
    str += '<img class="profile" src="' + sender.profile_image_url + '" onclick="openTab(\'' + TBASE + sender.screen_name + '\')"></img>';
    str += '<a href="#" class="user" " onclick="openTab(\'' + TBASE + sender.screen_name + '\')" title="' + sender.screen_name + '">' + sender.name + '</a>';

    str += '<div class="text">';
    str += text + '</div>';

    str += '<div class="footer">';
    str += '<span class="timestamp" title="' + getTimestampAltText(dm.created_at) + '">' + getTimestampText(dm.created_at) + '</span>';

    str += ' sent to ' +  dm.recipient.name;

    str += '</div></div>';

    str += '<div class="new_actions0">';


    str += '<img src="img/delete.png" title="删除" onclick="deleteTweet(this)"></img><br>';
    str += '<div class="del_confirm" style="display: none;">删除这条私信: <a href="javascript:confirmDelete(1);">确定</a> <a href="javascript:denyDelete();">取消</a></div>';
    //str += '<img src="img/reply.png" title="回复" onclick="replyTweet(this.parentNode.parentNode)"></img><br>';

    str += '</div>';
    str += '<div style="clear: both;"></div>';

    str += '</div>'
    return str;
}

function renderTweet(tweet) {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;

    TBASE = "http://t.163.com/";
    var user = tweet.user;
    var text = tweet.text;

    text = transformTweetText(text);

    var tweetClass = 'tweet';
    var from = null;
    if(tweet.source) {
	from = tweet.source.replace(/(href=(["''"])(.*?)\2)/i, "$1 onclick=\"openTab('$3')\"");
    }

    var tweetUserName = user.name;
    var tweetTitleUserName = user.screen_name;

    var str = '<div tweetid="' + tweet.id + '" user_name="' +  user.name + '" class="'
	+ tweetClass + '" onmouseover="this.children[1].className=\'new_actions1\';"'
	+ ' onmouseout="this.children[1].className=\'new_actions0\';" >';
    str += '<div class="first_container">';
    str += '<img class="profile" src="' + user.profile_image_url + '" onclick="openTab(\'' + TBASE + user.screen_name + '\')"></img>';
    str += '<a href="#" class="user" " onclick="openTab(\'' + TBASE + user.screen_name + '\')" title="' + tweetTitleUserName + '">' + tweetUserName + '</a>';

    str += '<div class="text">';
    str += text + '</div>';

    str += '<div class="footer">';
    var statusLinkDst = TBASE + user.screen_name + '/status/' + tweet.id;
    str += '<a href="#" onclick="openTab(\'' + statusLinkDst + '\')"><span class="timestamp" title="' + getTimestampAltText(tweet.created_at) + '">' + getTimestampText(tweet.created_at) + '</span></a> ';

    if (from) {
      str += 'from ' + from;
    }

    var inReply = null;
    if(tweet.in_reply_to_status_id) {
      var linkDst = TBASE + tweet.in_reply_to_screen_name + '/status/' + tweet.in_reply_to_status_id;
	inReply = ' Re: ' + '<a href="' + linkDst + '" onclick="openTab(\'' + linkDst + '\')" title="' + tweet.in_reply_to_status_text + '">' + tweet.in_reply_to_status_text + '</a> ';
    }
    if (inReply) {
      str += inReply;
    }

    str += '</div></div>';

    str += '<div class="new_actions0">';

    if (backend.faved[tweet.id] == 1 || backend.faved[tweet.id] == null && tweet.favorited) {
	str += '<img src="img/star_hover.png" title="取消收藏" class="starred" onclick="unfavTweet(this.parentNode.parentNode);"></img><br>';
    } else {
	str += '<img src="img/star.png" title="收藏" class="unstarred" onclick="favTweet(this.parentNode.parentNode);"></img><br>';
    }

    if (tweet.user.screen_name == backend.user_screen_name) {
	str += '<img src="img/delete.png" title="删除" onclick="deleteTweet(this)"></img><br>';
	str += '<div class="del_confirm" style="display: none;">删除这条微博: <a href="javascript:confirmDelete();">确定</a> <a href="javascript:denyDelete();">取消</a></div>';
    } else {
	str += '<img src="img/reply.png" title="回复" onclick="replyTweet(this.parentNode.parentNode)"></img><br>';
	str += '<img src="img/share.png" title="转发" onclick="shareTweet(this.parentNode.parentNode)"></img><br>';
    }
    str += '</div>';
    str += '<div style="clear: both;"></div>';

    str += '</div>'
    return str;
}

function showTweets(id) {
    var backend = chrome.extension.getBackgroundPage().TweetManager.instance;

    if (id == -1) {
    	id = backend.currentTabId;
    } else {
	backend.currentTabId = id;
    }

    var names = ["home", "mentions", "mine", "favorites", "inbox", "sent"];
    console.log("showTweets " + id);

    var dom= document.getElementById("tab_modifier_home");
    if (id != 0 && backend.unread[0].length > 0) {
	var width = parseInt(window.getComputedStyle(dom.parentNode, "").getPropertyValue("width")) - 12;
	dom.style.width = width + "px";
    } else if (id == 0) {
	dom.style.width = "0px";
    }

    dom = document.getElementById("tab_modifier_mentions");
    if (id != 1 && backend.unread[1].length > 0) {
	var width = parseInt(window.getComputedStyle(dom.parentNode, "").getPropertyValue("width")) - 12;
	dom.style.width = width + "px";
    } else if (id == 1) {
	dom.style.width = "0px";
    }


    for (var i = 0; i < names.length; i++) {
	dom = document.getElementById("timeline-" + names[i]);
	if (i != id) {
	    dom.style.display = "none";
	} else {
	    chrome.browserAction.setBadgeText({text:String('')});
	    var tweets;
	    var showlen = 30;
	    if (id < 2) {
		var ulen = backend.unread[id].length;
		for (var j = 0; j < ulen ; j++) {
		    backend.read[id].unshift(backend.unread[id].pop());
		}

		tweets = backend.read[id];
		if (id == 0) {
		    localStorage.home_read_minid = backend.home_read_minid = tweets[0].id;
		} else if (id == 1) {
		    localStorage.mentions_read_minid = tweets[0].id;
		}
		showlen = Math.max(ulen, 30);
	    } else if (id == 2) {
		tweets = backend.mine;
	    } else if (id == 3) {
		tweets = backend.favorites;
	    } else if (id == 4) {
		tweets = backend.inbox
	    } else if (id == 5) {
		tweets = backend.sent
	    }
	    showlen = Math.min(tweets.length, showlen);
	    var tweetsArray = [];
	    for(var j = 0; j < showlen; ++j) {
		if (id > 3) {
		    if (backend.deleted_dm[tweets[j].id] == 1)
			continue;
		    tweetsArray[j] = renderDM(tweets[j]);
		} else {
		    if (backend.deleted[tweets[j].id] == 1)
			continue;
		    if (id == 3) { // fav
			if (backend.faved[tweets[j].id] == 0)
			    continue;
		    }
		    tweetsArray[j] = renderTweet(tweets[j]);
		}
	    }
	    dom.innerHTML = tweetsArray.join('');
	    dom.style.display = "block";
	}
    }
}

function onSelectTab(id) {
    showTweets(id);
}
